// page/detail/index.js
import { throttle, formateObjToParamStr, transformArr } from '/utils/util';
import { INITIAL_STATE } from '../../store/store';
import IMController from '../../controller/im'
import create from '/utils/create';
import WxParse from '../../wxParse/wxParse';
import wxApi from '/utils/wxapi';
import { mapApi, mapKey, constant, addr } from '/utils/config';
import {
  attention,
  unAttention,
  projectDetailBaseInfo,
  projectPhotographAlbumList,
  projectDetailHouseType,
  attentionHouse,
  unAttentionHouse,
  lookHouse,
  canBeRecommend,
  addEmployee,
  consultProject,
  action,
  getImInfo,
} from './services/index';
import { getSwtichByCode } from '../index/services/index';
import houseDetail from './houseDetail';
import ImgLoader from '../../img-loader/img-loader';
import store from '../globalStore';
import diff from '/utils/diff';
import { wxUserInfo } from '../my/services/index';
let app = getApp();
let appStore = app.store;
create.Page({
  ...houseDetail, // 房源详情逻辑代码
  store,
  /**
   * 页面的初始数据
   */
  data: {
    showsharebomb: false,
    showposter: false,
    currentIndex: 0,
    topSwiperIndex: 1,
    swiperConfig: {
      indicatorDots: false,
      autoplay: true,
      interval: 3000,
      duration: 500,
      indicatorActiveColor: '#5473E8',
    },
    detailData: {
      imgUrls: [
        'http://shop.brc.com.cn/uploaded/20181228160328_887.jpg',
        'http://shop.brc.com.cn/uploaded/20181228160338_697.jpg',
        'http://shop.brc.com.cn/uploaded/20181228160342_697.jpg',
      ],
      tabsData: {},
    },
    commission: '',
    richText: '<div style="text-align: center;font-size: 16px;margin-top: 20px">我是富文本</div>',
    mapTabs: ['公交', '地铁', '教育', '医院'],
    mapData: {
      marks: [],
      latitude: '',
      longitude: '',
    },
    isShow: false,
    attentionIcon: 'icon-shoucang1',
    baseInfo: {
      isShowRecommendBtn: true,
    }, // 头部信息
    bannerList: {}, // 轮播图
    plotDetail: {}, // 楼盘信息
    houseDetailSearch: [], // 房源信息tab
    buildingList: [], // 楼栋名称列表
    houseList: [], // 房源列表
    unitCurrent: 0,
    typeCurrent: 0,
    floorCurrent: 0,
    isShowMore: false,
    bg: `${constant.imgUrl}gift/moreBg.png`,
    buildingId: '',
    isShowTop: false,
    houseData: {}, // 房源详情
    qualificationsList: [], // 购房资格
    houseId: '', // 弹出的房间id
    tabOF: false,
    housePrF: false,
    identitysLen: 0,
    businessCardId: '',
    disabled: false
  },
  sharefn () {
    this.setData({
      showsharebomb: true,
    });
  },
  onPageScroll (e) {
    if (e.scrollTop > this.data.tabTop) {
      if (!this.data.isToTop) {
        console.log('eee---222', e);
        this.setData({
          isToTop: true,
        });
      }
    } else {
      if (this.data.isToTop) {
        console.log('eee---333', e);
        this.setData({
          isToTop: false,
        });
      }
    }

    if (e.scrollTop > 50) {
      if (!this.data.isShowTop) {
        this.setData({
          isShowTop: true,
        });
      }
    } else {
      if (this.data.isShowTop) {
        this.setData({
          isShowTop: false,
        });
      }
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    getSwtichByCode({
      code: 'PROJECT_READ_INFO_SWITCH',
    }).then(res => {
      if (res.code === constant.codeSuccess) {
        if (res.data.status === 'ON') {
          this.setData({
            tabOF: true,
          });
          // this.getProjectDetailHouseType(true);
        } else {
          this.getProjectDetailHouseType();
          this.setData({
            currentIndex: 1,
            tabOF: false,
          });
        }
      }
    });

    getSwtichByCode({
      code: 'HOUSE_TYPE_PRICE_SHOW_SWITCH',
    }).then(res => {
      if (res.code === constant.codeSuccess) {
        if (res.data.status === 'ON') {
          this.setData({
            housePrF: true,
          });
        } else {
          this.setData({
            housePrF: false,
          });
        }
      }
    });
    console.log('options---', options);
    // 跳转房源信息
    if (options.current) {
      const current = Number(options.current);
      this.setData({
        currentIndex: current,
      });
      this.getProjectBuildingList(current, options.projectId);
    }
    // 请求楼盘信息

    if (options.projectId) {
      const projectId = options.projectId;
      this.store.data.projectId = options.projectId;
      this.setData({
        projectId: projectId,
      });

      // if (this.store.data.detailBaseInfo) {
      //   const data = this.store.data.detailBaseInfo;
      //   this.setData({
      //     baseInfo: data,
      //   });

      //   this.setPreloadImg(data.readInfo);
      //   if (data.isAttention) {
      //     this.oData.attentionIcon = 'icon-shoucang';
      //   }
      // } else {
      //   this.getProjectDetailBaseInfo(projectId);
      // }
      this.getProjectDetailBaseInfo(projectId);

      this.getProjectPhotographAlbumList(projectId);
    }
    // 获取tab高度
    this.getTabHeight();
    this.imgLoader = new ImgLoader(this);
    this.onEmitter();
  },
  onShow () {
    wxUserInfo().then(res => {
      if (res.code === constant.codeSuccess) {
        // console.log('', res);
        this.setData({
          identitysLen: res.data.identitys ? res.data.identitys.length : 0,
        });
      }
    });
    this.doLogin();
    this.setData({
      disabled: false
    })
  },
  onUnload () {
    this.OffEmitter();
  },
  doLogin () {
    const accid = wx.getStorageSync('accid');
    const imToken = wx.getStorageSync('imToken');
    if (accid) {
      if (app.globalData.nim) {
      } else {
        new IMController({
          account: accid,
          token: imToken,
        });
      }
    }
  },
  onEmitter () {
    const that = this;
    // 监听
    this.store.emitter.on('currentIndex', this.changeTabs);
    this.store.emitter.on('mapCurrent', this.changeMapTabs);
    this.store.emitter.on('changeBuild', this.changeBuild);
    this.store.emitter.on('changeUnit', this.changeUnit);
    this.store.emitter.on('changeType', this.changeType);
    this.store.emitter.on('changeFloor', this.changeFloor);
    this.store.emitter.on('toShowDetail', this.toShowDetail);
    this.store.emitter.on('imgOk', this.setRichImg);
    this.store.emitter.off('toLookHouse', this.toLookHouse);
    this.store.emitter.on('toAttention', this.toAttention);
    this.store.emitter.on('toAttentionHouse', this.toAttentionHouse);
    this.store.emitter.on('openChooseStatus', this.openChooseStatus);
    this.store.emitter.on('toHouseCar', this.toHouseCar);
    this.store.emitter.on('showposterlocation', e => {
      that.setData({
        showposter: e.show,
      });
    });
    this.store.emitter.on('showsharebomblocation', e => {
      that.setData({
        showsharebomb: e.show,
      });
    });
    this.store.emitter.on('showLoading', v => {
      this.setData({
        isShowLoading: v,
      });
    });
  },
  OffEmitter () {
    this.store.emitter.off('currentIndex');
    this.store.emitter.off('mapCurrent');
    this.store.emitter.off('changeBuild');
    this.store.emitter.off('changeUnit');
    this.store.emitter.off('changeType');
    this.store.emitter.off('changeFloor');
    this.store.emitter.off('toShowDetail');
    this.store.emitter.off('imgOk');
    this.store.emitter.off('toLookHouse');
    this.store.emitter.off('toAttention');
    this.store.emitter.off('toAttentionHouse');
    this.store.emitter.off('openChooseStatus');
    this.store.emitter.off('toHouseCar');
    this.store.emitter.off('showposterlocation');
    this.store.emitter.off('showsharebomblocation');
  },
  toRecomment (e) {
    const { projectId } = this.data;
    if (this.store.data.phone) {
      this.store.data.phone = null;
    }
    canBeRecommend({
      projectId,
    }).then(res => {
      console.log('1111111-------', res.code);
      const { imgurl, title, id } = e.currentTarget.dataset;
      if (res.code === constant.codeSuccess) {
        wx.navigateTo({
          url: `/page/invite/index?imgurl=${imgurl}&title=${title}&id=${id}`,
        });
        return null;
      } else if (res.code === 'E_RECOMMEND_NO_ID_CARD') {
        this.store.data.id = id;
        this.store.data.imgurl = imgurl;
        this.store.data.title = title;
        console.log(this.store.data.imgurl, '-------------', this.store.data.title);
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 1000,
          complete: setTimeout(() => {
            wx.navigateTo({
              url: '/page/identity/index?from=detail',
            });
          }, 1000),
        });

        return null;
      } else if (res.code === 'E_RECOMMEND_NO_BAND_CARD') {
        this.store.data.id = id;
        this.store.data.imgurl = imgurl;
        this.store.data.title = title;
        console.log(this.store.data.imgurl, '-------------', this.store.data.title);
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 1000,
          complete: setTimeout(() => {
            wx.navigateTo({
              url: `/page/addBankCard/index?from=detail&projectId=${projectId}`,
            });
          }, 1000),
        });
        return null;
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 3000,
        });
      }
    });
    return null;
  },
  getProjectDetailBaseInfo (projectId) {
    projectDetailBaseInfo({
      projectId,
    }).then(res => {
      if (res.code === constant.codeSuccess) {
        const diffRel = diff(res.data, this.data.baseInfo);
        if (res.data.commissionInfo) {
          // let a = '推荐人推荐客户成功购买江山美宸项目除车位和特殊优惠产品可得成交总金额税前0.20%。'
          this.setData({
            commission: res.data.commissionInfo,
            // commission: a
          });
        }
        if (Object.keys(diffRel).length) {
          // console.log('数据改变重新设置---', diffRel);
          const rel = {};
          Object.keys(diffRel).forEach(v => {
            rel['baseInfo.' + v] = diffRel[v];
          });
          this.setData(rel);
        } else {
          console.warn('数据未改变');
        }
        this.setPreloadImg(res.data.readInfo);
        if (res.data.isAttention) {
          this.oData.attentionIcon = 'icon-shoucang';
        }
      }
    });
  },
  setPreloadImg (readInfo) {
    // console.log('readInfo-----111', readInfo);
    if (readInfo) {
      // const imgReg = /<img.*?(?:>|\/>)/gi;
      // const srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
      // const arr = readInfo.match(imgReg);
      // if (arr.length) {
      //   // 暂时替换一张
      //   arr.length = 1;
      //   for (let i = 0; i < arr.length; i++) {
      //     let src = arr[i].match(srcReg)[1];
      //     if (src) {
      //       const i = src.lastIndexOf('.');
      //       const fir = src.slice(0, i);
      //       const last = src.slice(i);
      //       const url = fir + '_thumb' + last;
      //       console.log('src---', src, url);
      //       readInfo = readInfo.replace(src, url);
      //     }
      //   }
      // }
      // console.log('readInfo-----222', readInfo);
    }

    this.makeRichText(readInfo);
  },
  setRichImg () {
    // console.log('富文本图片加载完成');
    this.makeRichText(this.data.baseInfo.readInfo);
  },
  getProjectPhotographAlbumList (projectId) {
    projectPhotographAlbumList({
      projectId,
    }).then(res => {
      if (res.code === constant.codeSuccess) {
        this.oData.bannerList = res.data;
      }
    });
  },
  getProjectDetailHouseType (houseType) {
    projectDetailHouseType({
      projectId: this.data.projectId,
    }).then(res => {
      if (res.code === constant.codeSuccess) {
        // 获取略缩图
        let houseVr = [];
        res.data.houseTypeList.forEach(v => {
          let pic = v.houseTypePic;
          if (v.vrUrl) {
            houseVr.push(v);
          }
          // console.log('pic---', pic);
          if (!pic) return;
          const i = pic.lastIndexOf('.');
          const fir = pic.slice(0, i);
          const last = pic.slice(i);
          v.thumbPic = fir + '_thumb' + last;
          this.imgLoader.load(pic, (err, data) => {
            if (!err) {
              // console.log('户型预加载成功', data);
            }
          });
        });

        const arr = transformArr(res.data.houseTypeList, 2);
        res.data.houseTypeListLen = res.data.houseTypeList.length;
        res.data.houseTypeList = arr;
        this.store.data.houseTypeVr = houseVr;
        // console.log('法规的规定法国代购', this.store, houseVr);
        const { latitude, longitude } = res.data;
        res.data.latitude = Number(latitude);
        res.data.longitude = Number(longitude);
        // diff数据
        const diffRel = diff(res.data, this.data.plotDetail);
        if (!Object.keys(diffRel).length) {
          return;
        } else {
          console.warn('数据改变了');
        }
        this.setData(
          {
            plotDetail: res.data,
            mapData: {
              ...this.data.mapData,
              latitude,
              longitude,
            },
          },
          () => {
            if (houseType) return;
            this.getAddr();
            this.changeMapTabs({ item: '公交' });
          }
        );
      }
    });
  },
  makeRichText (readInfo) {
    var that = this;
    WxParse.wxParse('article', 'html', readInfo || '', that, 0);
  },
  changeTabs (e) {
    // console.log('选中的tab---', e);
    if (this.data.isToTop) {
      wx.pageScrollTo({
        scrollTop: this.data.tabTop,
        duration: 0,
      });
    }
    switch (e) {
      case 0:
        this.getProjectDetailBaseInfo(this.data.projectId);
        this.setData({
          currentIndex: e,
        });
        break;
      case 1:
        this.getProjectDetailHouseType();
        this.setData({
          currentIndex: e,
        });
        break;
      case 2:
        this.getProjectBuildingList(e);
        break;
      default:
        break;
    }
  },
  getTabHeight () {
    let query = wx.createSelectorQuery();
    query
      .select('#tabs')
      .boundingClientRect(res => {
        this.data.tabTop = res.top;
      })
      .exec();
  },
  toTop () {
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 900,
    });
  },
  topSwiperChange (e) {
    this.setData({
      topSwiperIndex: e.detail.current + 1,
    });
  },
  changeMapTabs (e) {
    console.log('切换地图', e);
    const { latitude, longitude } = this.data.mapData;

    wxApi('request', {
      url: mapApi,
      data: {
        keyword: e.item,
        boundary: `nearby(${latitude},${longitude},1000)`,
        key: mapKey,
      },
    }).then(
      res => {
        // console.log('e---', res);
        if (res.statusCode === 200 && res.data.status === 0) {
          const markers = [];
          // console.log('ditu');
          // console.log(res.data.data);
          res.data.data.forEach(v => {
            markers.push({
              latitude: v.location.lat,
              longitude: v.location.lng,
              title: v.title,
              iconPath: '../../../../assets/images/location.png',
              width: '30rpx',
              height: '40rpx',
            });
          });
          const { latitude, longitude } = this.data.mapData;
          markers.push({
            longitude,
            latitude,
            title: this.data.plotDetail.projectAddress,
            iconPath: '../../../../assets/images/center.png',
            zIndex: 999,
            width: '30rpx',
            height: '40rpx',
          });
          this.setData({
            'mapData.marks': markers,
          });
        } else {
          wx.showToast({
            title: '地图接口超限制！',
            icon: 'none',
          });
        }
      },
      err => {
        wx.showToast({
          title: '地图接口超限制！',
          icon: 'none',
        });
      }
    );
  },
  getAddr () {
    wxApi('request', {
      url: addr,
      data: {
        address: this.data.plotDetail.saleAddress,
        key: mapKey,
      },
    }).then(res => {
      // console.log('e---', res);
      if (res.statusCode === 200 && res.data.status === 0) {
        this.setData({
          saleAddressLocation: res.data.result.location,
        });
      }
    });
  },
  toCall () {
    if (!this.data.identitysLen) {
      wx.navigateTo({
        url: '/page/detailToUser/index?from=user',
      });
      return;
    }
    this.setData({
      isShow: true,
    });
  },
  cancel () {
    // console.log('隐藏');
    this.setData({
      isShow: false,
    });
  },
  confirm () {
    // console.log('确认');
    const { phone, subPhone } = this.data.baseInfo;
    wx.makePhoneCall({
      phoneNumber: phone + ',' + subPhone,
      success: () => {
        this.setData({
          isShow: false,
        });
      },
    });
  },
  toLookHouse () {
    const projectId = this.data.projectId;
    const housePrF = this.data.housePrF;
    wx.navigateTo({
      url: `/page/detailType/index?id=${projectId}&housePrF=${housePrF}`,
    });
  },
  toAttention () {
    const projectId = this.data.projectId;
    if (this.data.attentionIcon === 'icon-shoucang1') {
      attention({
        projectId,
      }).then(res => {
        if (res.code === constant.codeSuccess) {
          this.oData.attentionIcon = 'icon-shoucang';
          this.getProjectDetailBaseInfo(this.data.projectId);
        }
      });
    } else {
      unAttention({
        projectId,
      }).then(res => {
        if (res.code === constant.codeSuccess) {
          this.oData.attentionIcon = 'icon-shoucang1';
          this.getProjectDetailBaseInfo(this.data.projectId);
        }
      });
    }
  },
  toAttentionHouse (houseId) {
    if (!this.data.houseData.isAttention) {
      attentionHouse({
        houseId,
      }).then(res => {
        if (res.code === constant.codeSuccess) {
          this.getBuildingHouseList();
          this.toShowDetail({
            houseId: this.data.houseId,
          });
        }
      });
    } else {
      unAttentionHouse({
        houseId,
      }).then(res => {
        if (res.code === constant.codeSuccess) {
          this.getBuildingHouseList();
          this.toShowDetail({
            houseId: this.data.houseId,
          });
        }
      });
    }
  },
  showMore () {
    this.oData.isShowMore = true;
    var that = this;
    WxParse.wxParse('dialogCont', 'html', that.data.baseInfo.discountRemarks || '', that, 0);
  },
  closeDialog () {
    this.oData.isShowMore = false;
  },
  scroll () {
    return null;
  },
  toAppointment () {
    // console.log('toAppointment', this.data.identitysLen);
    if (!this.data.identitysLen) {
      wx.navigateTo({
        url: '/page/detailToUser/index?from=user',
      });
      return;
    }
    lookHouse({
      projectId: this.data.projectId,
    }).then(res => {
      if (res.code === constant.codeSuccess) {
        wx.showToast({
          title: res.data,
          icon: 'none',
          duration: 2000,
        });
      } else {
        wx.showToast({
          title: res.message,
          icon: 'none',
          duration: 2000,
        });
      }
    });
  },
  onShareAppMessage: function () {
    return {
      desc: '蓝裔云',
      title: `${this.data.baseInfo.projectName}/${this.data.baseInfo.city}${
        this.data.baseInfo.hidePrice ? `/\n${this.data.baseInfo.hidePrice}元/m²起！` : ''
        }`,
      path: `/page/loading/index?id=${this.data.projectId}&page=1`,
      imageUrl: '',
    };
  },
  vr () {
    // console.log('vr');
  },
  getImInfo (accid, session) {
    wx.navigateTo({
      url: `../../partials/chating/index?chatTo=${accid}&cardId=${this.data.businessCardId}`,
    })
    app.globalData.nim.resetSessionUnread(session)
  },
  getImCardInfo () {
    const that = this
    consultProject({ bfPorjectId: this.data.projectId })
      .then(res => {
        if (res.code === constant.codeSuccess) {
          that.setData({
            businessCardId: res.data.businessCardId || ''
          })
          if (!INITIAL_STATE.isLogin) {
            that.addEmployeeDone(res.data)
          } else {
            wx.showLoading({
              title: '',
              mask: true,
            })
            setTimeout(() => {
              wx.hideLoading()
              that.addEmployeeDone(res.data)
            }, 3000)
          }
        }
      })
      .catch(err => {
        that.setData({
          disabled: false
        })
        console.log(err);
      });
  },
  goChat () {
    if (!this.data.disabled) {
      const that = this
      this.setData({
        disabled: true
      })
      this.getImCardInfo()
    }
  },
  addEmployeeDone (params) {
    addEmployee({ wxUserId: params.wxUserId })
      .then(res => {
        if (res.code === constant.codeSuccess) {
          let session = `p2p-${params.accid}`;
          appStore.dispatch({
            type: 'CurrentChatTo_Change',
            payload: session,
          });
          app.globalData.nim.addFriend({
            account: params.accid,
            ps: '',
            done: this.addFriendDone,
          });
        } else if (res.code === 'E0009') {
          wx.switchTab({
            url: `../recentchat/index`,
          });
        }
      })
      .catch(err => {
        console.log(err);
      });
  },
  addFriendDone (error, obj) {
    let that = this;
    console.log('直接加为好友' + (!error ? '成功' : '失败'), error, obj);
    if (!error) {
      appStore.dispatch({
        type: 'FriendCard_Add_Friend',
        payload: obj.friend,
      });
      app.globalData.nim.getUser({
        account: obj.friend.account,
        done: function (err, user) {
          console.log('user');
          console.log(user);
          appStore.dispatch({
            type: 'FriendCard_Add_Friend',
            payload: user,
          });
          let session = `p2p-${user.account}`;
          that.getImInfo(user.account, session);
        },
      });
    } else {
      this.setData({
        disabled: false
      })
      const accid = wx.getStorageSync('accid')
      const imToken = wx.getStorageSync('imToken')
      app.globalData.nim.destroy({
        done: function () {
          console.log('destroy nim done !!!')
          new IMController({
            account: accid,
            token: imToken,
          });
        }
      })
    }
  },
});
